﻿using System.Collections.Generic;
using System.ServiceModel;
using Ipmce.RemoteVoting.Backend.DataAccess;
using Ipmce.RemoteVoting.Backend.VotingService.Contract;
using Candidate = Ipmce.RemoteVoting.Common.Entities.Candidate;
using ICandidateListProvider = Ipmce.RemoteVoting.Backend.VotingService.Contract.ICandidateListProvider;

namespace Ipmce.RemoteVoting.Backend.VotingService
{
	public class VotingService : IPassportVoting, ICertificateVoting, ICandidateListProvider
	{
		public VotingService(DataAccess.ICandidateListProvider dataCandidateListProvider,
			IVoterRepository voterRepository)
		{
			_dataCandidateListProvider = dataCandidateListProvider;
			_voterRepository = voterRepository;
		}

		void IPassportVoting.Vote(byte[] vote, string confirmationId)
		{
			var identity = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;
			var voter = _voterRepository.GetByPassportNumber(identity.Name);
			Vote(voter, vote, confirmationId);
		}

		void ICertificateVoting.CertificateVote(byte[] vote, string confirmationId)
		{
			var identity = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;
			var thumbPrint = identity.Name.Substring(identity.Name.LastIndexOf(';') + 2);
			var voter = _voterRepository.GetByThumbprint(thumbPrint);
			Vote(voter, vote, confirmationId);
		}

		public IList<Candidate> GetCandidateList()
		{
			return _dataCandidateListProvider.GetCandidateList();
		}

		private void Vote(Voter voter, byte[] vote, string confirmationId)
		{
			voter.Vote = vote;
			voter.ConfirmationId = confirmationId;
			_voterRepository.CommitChanges();
		}

		private readonly DataAccess.ICandidateListProvider _dataCandidateListProvider;
		private readonly IVoterRepository _voterRepository;
	}
}
